<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-row :gutter="15" align="middle">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input
            v-model="searchName"
            placeholder="请输入被调查人姓名"
            clearable
            style="width: 100%;"
            size="large"
          />
        </el-col>
        
        <!-- 按钮组 -->
        <el-col :span="16" class="button-group">
          <el-button 
            type="info" 
            size="large" 
            icon="Search" 
            @click="handleSearch"
          >
            查询
          </el-button>

          <el-button 
            type="primary" 
            size="large" 
            icon="Download" 
            @click="showImportDialog"
          >
            导入
          </el-button>
          
          <el-button 
            type="success" 
            size="large" 
            icon="Plus" 
            @click="showAddDialog"
          >
            新增
          </el-button>

          <el-button 
            type="warning" 
            size="large" 
            icon="Upload" 
            @click="exportData"
          >
            导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="card-container">
      <div class="table-wrapper">
        <el-table :data="disciplineList" border class="full-height-table"
            :header-cell-style="{ background: '#f0f0f0' }">
                   <!-- 序号列 -->
          <el-table-column type="index" label="序号" align="center" width="60">
            <template #default="scope">
              {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="report_unit_name" label="填报单位名称" align="center" width="150"></el-table-column>
          <el-table-column prop="report_unit_code" label="填报单位代码" align="center" width="150"></el-table-column>
          <el-table-column prop="investigated_person" label="被调查人" align="center" width="120"></el-table-column>
          <el-table-column prop="work_unit_and_position" label="工作单位及职务" align="center" width="230"></el-table-column>
          <el-table-column prop="rank" label="职级" align="center" width="100"></el-table-column>
          <el-table-column prop="case_code" label="案件编码" align="center" width="150"></el-table-column>
          <el-table-column prop="id_number" label="身份证号" align="center" width="210"></el-table-column>
          <el-table-column prop="filing_time" label="立案时间" align="center" width="150"></el-table-column>
          <el-table-column prop="closing_time" label="结案时间" align="center" width="150"></el-table-column>
          <el-table-column prop="party_discipline_punishment" label="党纪处分" align="center" width="120"></el-table-column>
          <el-table-column prop="administrative_punishment" label="政务处分" align="center" width="120"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                :icon="Edit" 
                @click="handleEdit(scope.row)" 
              />
              <el-button 
                size="small" 
                :icon="Delete" 
                @click="handleDelete(scope.row.id)" 
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" top="5vh">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px">
        <el-row :gutter="20">
          <!-- 第一列：基本信息、案件信息、个人信息 -->
          <el-col :span="6">
            <el-divider content-position="left">基本信息</el-divider>
            <el-form-item label="填报单位名称" prop="report_unit_name">
              <el-input v-model="form.report_unit_name" placeholder="请输入填报单位名称" />
            </el-form-item>
            <el-form-item label="填报单位代码" prop="report_unit_code">
              <el-input v-model="form.report_unit_code" placeholder="请输入填报单位代码" />
            </el-form-item>
            <el-form-item label="被调查人" prop="investigated_person">
              <el-input v-model="form.investigated_person" placeholder="请输入被调查人" />
            </el-form-item>
            <el-form-item label="工作单位及职务" prop="work_unit_and_position">
              <el-input v-model="form.work_unit_and_position" placeholder="请输入工作单位及职务" />
            </el-form-item>
            <el-form-item label="职级" prop="rank">
              <el-input v-model="form.rank" placeholder="请输入职级" />
            </el-form-item>
            <el-form-item label="干部管理权限" prop="cadre_management_authority">
              <el-input v-model="form.cadre_management_authority" placeholder="请输入干部管理权限" />
            </el-form-item>
            <el-form-item label="中管干部二级" prop="central_managed_cadre_level2">
              <el-input v-model="form.central_managed_cadre_level2" placeholder="请输入中管干部二级" />
            </el-form-item>
            <el-form-item label="是否单位或事故" prop="is_unit_or_accident">
              <el-select v-model="form.is_unit_or_accident" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>

            <el-divider content-position="left">案件信息</el-divider>
            <el-form-item label="案件编码" prop="case_code">
              <el-input v-model="form.case_code" placeholder="请输入案件编码" />
            </el-form-item>
            <el-form-item label="涉案人员编码" prop="involved_person_code">
              <el-input v-model="form.involved_person_code" placeholder="请输入涉案人员编码" />
            </el-form-item>

            <el-divider content-position="left">个人信息</el-divider>
            <el-form-item label="证件类型" prop="id_type">
              <el-input v-model="form.id_type" placeholder="请输入证件类型" />
            </el-form-item>
            <el-form-item label="证件号码" prop="id_number">
              <el-input v-model="form.id_number" placeholder="请输入证件号码" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="请输入年龄" type="number" />
            </el-form-item>
            <el-form-item label="出生年月" prop="birth_date">
              <el-date-picker v-model="form.birth_date" type="date" placeholder="选择出生年月" />
            </el-form-item>
            <el-form-item label="学历" prop="education">
              <el-input v-model="form.education" placeholder="请输入学历" />
            </el-form-item>
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="form.ethnicity" placeholder="请输入民族" />
            </el-form-item>
          </el-col>

          <!-- 第二列：个人信息（续）、金额信息、立案信息等 -->
          <el-col :span="6">
            <el-divider content-position="left">个人信息（续）</el-divider>
            <el-form-item label="是否国家监察对象" prop="is_national_supervision_object">
              <el-select v-model="form.is_national_supervision_object" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="国家监察对象详情" prop="national_supervision_object_detail">
              <el-input v-model="form.national_supervision_object_detail" placeholder="请输入详情" />
            </el-form-item>
            <el-form-item label="是否中共党员" prop="is_ccp_member">
              <el-select v-model="form.is_ccp_member" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="中共党代表" prop="ccp_congress_representative">
              <el-input v-model="form.ccp_congress_representative" placeholder="请输入中共党代表" />
            </el-form-item>
            <el-form-item label="入党时间" prop="party_join_date">
              <el-date-picker v-model="form.party_join_date" type="date" placeholder="选择入党时间" />
            </el-form-item>
            <el-form-item label="人大代表" prop="npc_member">
              <el-input v-model="form.npc_member" placeholder="请输入人大代表" />
            </el-form-item>
            <el-form-item label="政协委员" prop="cppcc_member">
              <el-input v-model="form.cppcc_member" placeholder="请输入政协委员" />
            </el-form-item>
            <el-form-item label="影响期限结束时间" prop="impact_end_date">
              <el-date-picker v-model="form.impact_end_date" type="date" placeholder="请选择影响期限结束时间" />
            </el-form-item>

            <el-divider content-position="left">金额信息</el-divider>
            <el-form-item label="失职渎职金额" prop="misconduct_amount">
              <el-input v-model="form.misconduct_amount" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="违纪违法总金额" prop="total_violation_amount">
              <el-input v-model="form.total_violation_amount" placeholder="请输入金额" type="number" />
            </el-form-item>

            <el-divider content-position="left">立案信息</el-divider>
            <el-form-item label="立案统计时间" prop="filing_stat_time">
              <el-date-picker v-model="form.filing_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="立案时间" prop="filing_time">
              <el-date-picker v-model="form.filing_time" type="date" placeholder="选择立案时间" />
            </el-form-item>
            <el-form-item label="案件来源" prop="case_source">
               <el-input v-model="form.case_source" placeholder="请输入案件来源" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="巡视巡察中发现二级分类" prop="inspection_found_level2">
               <el-input v-model="form.inspection_found_level2" placeholder="请输入巡视巡察中发现二级分类" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="上级交办转办二级分类" prop="superior_assigned_level2">
               <el-input v-model="form.superior_assigned_level2" placeholder="请输入上级交办转办二级分类" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="纪委立案机关" prop="discipline_filing_agency">
               <el-input v-model="form.discipline_filing_agency" placeholder="请输入纪委立案机关" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="纪委立案时间" prop="discipline_filing_time">
               <el-date-picker v-model="form.discipline_filing_time" type="date" placeholder="选择纪委立案时间" />
            </el-form-item>
            <el-form-item label="纪委立案统计时间" prop="discipline_filing_stat_time">
               <el-date-picker v-model="form.discipline_filing_stat_time" placeholder="选择纪委立案统计时间" />
            </el-form-item>
            <el-form-item label="监委立案机关" prop="supervision_filing_agency">
               <el-input v-model="form.supervision_filing_agency" placeholder="请输入监委立案机关" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="监委立案时间" prop="supervision_filing_time">
               <el-date-picker v-model="form.supervision_filing_time" placeholder="选择监委立案时间"/>
            </el-form-item>
            <el-form-item label="监委立案统计时间" prop="supervision_filing_stat_time">
               <el-date-picker v-model="form.supervision_filing_stat_time" placeholder="选择监委立案统计时间" />
            </el-form-item>
          </el-col>

          <!-- 第三列：处分信息、司法处理、经济处理等 -->
          <el-col :span="6">
            <el-divider content-position="left">特征处理</el-divider>
            <el-form-item label="是否违反中央八项规定精神" prop="is_violate_central_regulations">
              <el-select v-model="form.is_violate_central_regulations" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否属于问责" prop="is_accountability_case">
              <el-select v-model="form.is_accountability_case" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否主动交代问题" prop="is_voluntary_confession">
              <el-select v-model="form.is_voluntary_confession" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>

            <el-divider content-position="left">处分信息</el-divider>
            <el-form-item label="党纪处分" prop="party_discipline_punishment">
              <el-input v-model="form.party_discipline_punishment" placeholder="请输入党纪处分" />
            </el-form-item>
            <el-form-item label="是否本应撤销党内职务但给予严重警告" prop="is_should_dismiss_but_given_warning">
              <el-select v-model="form.is_should_dismiss_but_given_warning" placeholder="请选择">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
            <el-form-item label="党纪处分统计时间" prop="party_punishment_stat_time">
              <el-date-picker v-model="form.party_punishment_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="政务处分" prop="administrative_punishment">
              <el-input v-model="form.administrative_punishment" placeholder="请输入政务处分" />
            </el-form-item>
            <el-form-item label="政务处分统计时间" prop="admin_punishment_stat_time">
              <el-date-picker v-model="form.admin_punishment_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>

            <el-divider content-position="left">司法处理</el-divider>
            <el-form-item label="移送检察机关时间" prop="transfer_prosecution_time">
              <el-date-picker v-model="form.transfer_prosecution_time" type="date" placeholder="选择移送时间" />
            </el-form-item>
            <el-form-item label="刑事处理主刑" prop="criminal_punishment_main">
              <el-input v-model="form.criminal_punishment_main" placeholder="请输入刑事处理主刑" />
            </el-form-item>
            <el-form-item label="刑事处理附加刑" prop="criminal_punishment_additional">
              <el-input v-model="form.criminal_punishment_additional" placeholder="请输入刑事处理附加刑" />
            </el-form-item>
            <el-form-item label="主刑年数" prop="main_sentence_years">
              <el-input v-model="form.main_sentence_years" placeholder="请输入年数" type="number" />
            </el-form-item>
            <el-form-item label="主刑月数" prop="main_sentence_months">
              <el-input v-model="form.main_sentence_months" placeholder="请输入月数" type="number" />
            </el-form-item>

            <el-divider content-position="left">经济处理</el-divider>
            <el-form-item label="挽回经济损失" prop="recover_economic_loss">
              <el-input v-model="form.recover_economic_loss" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="收缴金额" prop="recovery_amount">
              <el-input v-model="form.recovery_amount" placeholder="请输入金额" type="number" />
            </el-form-item>
            <el-form-item label="没收金额" prop="confiscation_amount">
              <el-input v-model="form.confiscation_amount" placeholder="请输入金额" type="number" />
            </el-form-item>

            <el-divider content-position="left">报告文件</el-divider>
            <el-form-item label="审查调查报告" prop="investigation_report">
              <el-input v-model="form.investigation_report" placeholder="请输入审查调查报告" />
            </el-form-item>
            <el-form-item label="审理报告" prop="trial_report">
              <el-input v-model="form.trial_report" placeholder="请输入审理报告" />
            </el-form-item>
            <el-form-item label="案件剖析" prop="case_analysis">
              <el-input v-model="form.case_analysis" placeholder="请输入案件剖析" />
            </el-form-item>

            <el-divider content-position="left">其他处分信息</el-divider>
            <el-form-item label="留党察看年限" prop="probation_period_years">
              <el-input v-model="form.probation_period_years" placeholder="请输入留党察看年限" type="number" />
            </el-form-item>
            <el-form-item label="企业级别" prop="enterprise_level">
              <el-input v-model="form.enterprise_level" placeholder="请输入企业级别" />
            </el-form-item>
            <el-form-item label="潜逃去向" prop="escape_destination">
              <el-input v-model="form.escape_destination" placeholder="请输入潜逃去向" />
            </el-form-item>
             <el-form-item label="潜逃去向细节" prop="escape_destination_detail">
              <el-input v-model="form.escape_destination_detail" placeholder="请输入潜逃去向细节" />
            </el-form-item>

          </el-col>

          <!-- 第四列：时间信息、纪检监察建议、涉外信息、新增字段等 -->
          <el-col :span="6">
            <el-divider content-position="left">时间信息</el-divider>
            <el-form-item label="首次违纪违法时间" prop="first_violation_time">
              <el-date-picker v-model="form.first_violation_time" type="date" placeholder="选择首次时间" />
            </el-form-item>
            <el-form-item label="末次违纪违法时间" prop="last_violation_time">
              <el-date-picker v-model="form.last_violation_time" type="date" placeholder="选择末次时间" />
            </el-form-item>
            <el-form-item label="结案统计时间" prop="closing_stat_time">
              <el-date-picker v-model="form.closing_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="结案时间" prop="closing_time">
              <el-date-picker v-model="form.closing_time" type="date" placeholder="选择结案时间" />
            </el-form-item>

            <el-divider content-position="left">纪检监察建议</el-divider>
            <el-form-item label="提出建议机构1" prop="suggesting_agency1">
              <el-input v-model="form.suggesting_agency1" placeholder="请输入机构名称" />
            </el-form-item>
            <el-form-item label="被建议单位1" prop="suggested_unit1">
              <el-input v-model="form.suggested_unit1" placeholder="请输入单位名称" />
            </el-form-item>
            <el-form-item label="建议类型1" prop="suggestion_type1">
              <el-input v-model="form.suggestion_type1" placeholder="请输入建议类型" />
            </el-form-item>
            <el-form-item label="建议内容1" prop="suggestion_content1">
              <el-input v-model="form.suggestion_content1" placeholder="请输入建议内容" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="提出建议时间1" prop="suggestion_time1">
              <el-date-picker v-model="form.suggestion_time1" type="date" placeholder="选择建议时间" />
            </el-form-item>

            <el-form-item label="提出建议机构2" prop="suggesting_agency2">
              <el-input v-model="form.suggesting_agency2" placeholder="请输入机构名称" />
            </el-form-item>
            <el-form-item label="被建议单位2" prop="suggested_unit2">
              <el-input v-model="form.suggested_unit2" placeholder="请输入单位名称" />
            </el-form-item>
            <el-form-item label="建议类型2" prop="suggestion_type2">
              <el-input v-model="form.suggestion_type2" placeholder="请输入建议类型" />
            </el-form-item>
            <el-form-item label="建议内容2" prop="suggestion_content2">
              <el-input v-model="form.suggestion_content2" placeholder="请输入建议内容" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="提出建议时间2" prop="suggestion_time2">
              <el-date-picker v-model="form.suggestion_time2" type="date" placeholder="选择建议时间" />
            </el-form-item>

            <el-divider content-position="left">涉外信息</el-divider>
            <el-form-item label="涉外类别" prop="foreign_related_category">
              <el-input v-model="form.foreign_related_category" placeholder="请输入涉外类别" />
            </el-form-item>
            <el-form-item label="涉及国家" prop="involved_country">
              <el-input v-model="form.involved_country" placeholder="请输入涉及国家" />
            </el-form-item>
            <el-form-item label="涉外统计时间" prop="foreign_related_stat_time">
              <el-date-picker v-model="form.foreign_related_stat_time" type="date" placeholder="选择统计时间" />
            </el-form-item>
            <el-form-item label="涉外信息摘要" prop="foreign_related_summary">
              <el-input v-model="form.foreign_related_summary" placeholder="请输入涉外信息摘要" type="textarea" :rows="2" />
            </el-form-item>

            <el-divider content-position="left">备注</el-divider>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注" type="textarea" :rows="2" />
            </el-form-item>
            </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
             <!-- 新增字段组 - 使用折叠面板 -->
            <el-collapse v-model="activeCollapseNames" class="custom-collapse">
              <!-- 党风廉政意见回复情况 -->
              <el-collapse-item title="党风廉政意见回复情况" name="1">
                <el-form-item label="党风廉政意见回复时间" prop="duty_ethics_reply_time">
                  <el-date-picker
                    v-model="form.duty_ethics_reply_time"
                    type="date"
                    placeholder="请选择回复时间"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="党风廉政意见回复类型" prop="duty_ethics_reply_type">
                  <el-select v-model="form.duty_ethics_reply_type" placeholder="请输入回复类型" filterable clearable>
                    <el-option 
                      v-for="type in duty_ethics_reply_types" 
                      :key="type" 
                      :label="type" 
                      :value="type" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="党风廉政意见回复涉及人次" prop="duty_ethics_reply_person_count">
                  <el-input
                    v-model.number="form.duty_ethics_reply_person_count"
                    type="number"
                    placeholder="请输入涉及人次"
                  />
                </el-form-item>
                <el-form-item label="党风廉政意见回复材料" prop="duty_ethics_reply_materials">
                  <el-input
                    v-model="form.duty_ethics_reply_materials"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入回复材料内容"
                  />
                </el-form-item>
              </el-collapse-item>

              <!-- 不如实报告个人有关事项受处理情况 -->
              <el-collapse-item title="不如实报告个人有关事项受处理情况" name="2">
                <el-form-item label="不如实报告处理时间" prop="false_report_handle_time">
                  <el-date-picker
                    v-model="form.false_report_handle_time"
                    type="date"
                    placeholder="请选择处理时间"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="不如实报告问题" prop="false_report_issue">
                  <el-input
                    v-model="form.false_report_issue"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入问题内容"
                  />
                </el-form-item>
                <el-form-item label="不如实报告处理情况" prop="false_report_disposal">
                  <el-input
                    v-model="form.false_report_disposal"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入处理情况"
                  />
                </el-form-item>
                <el-form-item label="不如实报告处分文号" prop="false_report_punishment_no">
                  <el-input v-model="form.false_report_punishment_no" placeholder="请输入处分文号" />
                </el-form-item>
                <el-form-item label="不如实报告备注" prop="false_report_remarks">
                  <el-input
                    v-model="form.false_report_remarks"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注信息"
                  />
                </el-form-item>
              </el-collapse-item>

              <!-- 其他反映廉政情况的材料 -->
              <el-collapse-item title="其他反映廉政情况的材料" name="3">
                <el-form-item label="其他廉政材料时间" prop="other_integrity_material_time">
                  <el-date-picker
                    v-model="form.other_integrity_material_time"
                    type="date"
                    placeholder="请选择材料时间"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="其他廉政材料名称" prop="other_integrity_material_name">
                  <el-input v-model="form.other_integrity_material_name" placeholder="请输入材料名称" />
                </el-form-item>
                <el-form-item label="其他廉政材料内容" prop="other_integrity_material_content">
                  <el-input
                    v-model="form.other_integrity_material_content"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入材料内容"
                  />
                </el-form-item>
                <el-form-item label="其他廉政材料形成部门" prop="other_integrity_material_department">
                  <el-input v-model="form.other_integrity_material_department" placeholder="请输入形成部门" />
                </el-form-item>
                <el-form-item label="其他廉政材料备注" prop="other_integrity_material_remarks">
                  <el-input
                    v-model="form.other_integrity_material_remarks"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注信息"
                  />
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
          </el-col>
        </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </template>
  </el-dialog>

    <!-- 导入Excel -->
    <el-dialog v-model="importDialogVisible" title="导入受党纪处分和组织处理情况" width="40%">
      <el-upload
        class="upload-excel"
        action="#"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".xlsx,.xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">仅支持.xlsx格式文件，需与模板字段一致</div>
         <div class="el-upload__tip" style="color: orangered;" slot="tip">（注意:请把Excel中的数字单元格设置为文本格式）</div>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确认导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue';
import TopNav from './navmenu.vue'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import dbClient from '../../utils/database.js'
import * as XLSX from 'xlsx';

// 导入相关响应式数据
const importDialogVisible = ref(false);
const fileList = ref([]);
let selectedFile = null;

// 搜索相关响应式数据
const searchName = ref('');

// 分页相关响应式数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const duty_ethics_reply_types = import.meta.env.VITE_DUTY_ETHICS_REPLY_TYPES?.split(',') || [];
// 折叠面板活动项
const activeCollapseNames = ref(['1', '2', '3']);

// 受党纪处分列表
const disciplineList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({
  // 基本信息
  report_unit_name: '',
  report_unit_code: '',
  investigated_person: '',
  work_unit_and_position: '',
  rank: '',
  cadre_management_authority: '',
  central_managed_cadre_level2: '',
  is_unit_or_accident: '',

  // 案件信息
  case_code: '',
  involved_person_code: '',

  // 个人信息
  id_type: '',
  id_number: '',
  gender: '',
  age: null,
  birth_date: '',
  education: '',
  ethnicity: '',
  is_national_supervision_object: '',
  national_supervision_object_detail: '',
  is_ccp_member: '',
  ccp_congress_representative: '',
  party_join_date: '',
  npc_member: '',
  cppcc_member: '',
  impact_end_date:'',

  // 个人信息（补充）
  non_party_non_supervision: '',
  non_party_non_supervision_detail: '',
  is_discipline_inspection_official: '',
  discipline_inspection_committee: '',
  party_committee: '',
  current_position_start_date: '',
  principal_violation: '',
  principal_detail1: '',
  principal_detail2: '',
  principal_rank: '',
  department_category: '',
  department_category1: '',
  enterprise_nature: '',
  enterprise_nature1: '',
  enterprise_personnel_category: '',
  enterprise_position: '',

  // 金额信息
  misconduct_amount: null,
  total_violation_amount: null,

  // 立案信息
  filing_stat_time: '',
  filing_time: '',
  case_source: '',

  // 立案信息（补充）
  inspection_found_level2: '',
  superior_assigned_level2: '',
  discipline_filing_agency: '',
  discipline_filing_time: '',
  discipline_filing_stat_time: '',
  supervision_filing_agency: '',
  supervision_filing_time: '',
  supervision_filing_stat_time: '',
  is_transferred_after_filing: '',
  transfer_method: '',
  transfer_unit: '',
  brief_case_description: '',
  filing_report: '',
  filing_decision: '',

  // 特征信息（补充）
  is_violate_central_regulations: '',
  is_accountability_case: '',
  is_voluntary_confession: '',

  // 处分信息
  party_discipline_punishment: '',
  is_should_dismiss_but_given_warning: '',
  party_punishment_stat_time: '',
  administrative_punishment: '',
  admin_punishment_stat_time: '',

   // 处分信息（补充）
  other_treatment: '',
  other_treatment_stat_time: '',

  // 司法处理
  transfer_prosecution_time: '',
  criminal_punishment_main: '',
  criminal_punishment_additional: '',
  main_sentence_years: null,
  main_sentence_months: null,

  // 司法处理（补充）
  transfer_prosecution_stat_time: '',
  probation_years: null,
  probation_months: null,
  court_judgment_stat_time: '',

  // 经济处理
  recover_economic_loss: null,
  recovery_amount: null,
  confiscation_amount: null,

  // 经济处理（补充）
  order_refund_amount: null,
  register_submit_amount: null,
  recover_loss_due_to_misconduct: null,

  // 时间信息
  first_violation_time: '',
  last_violation_time: '',
  closing_stat_time: '',
  closing_time: '',

  // 时间信息（补充）
  other_violation_time: '',
  escape_time: '',
  escape_stat_time: '',

  // 审理信息（补充）
  trial_accept_time: '',
  trial_accept_stat_time: '',
  trial_agency: '',
  trial_completion_time: '',
  trial_completion_stat_time: '',
  punishment_decision: '',
  court_judgment_time: '',
  judicial_judgment_amount: null,

  // 报告文件（补充）
  investigation_report: '',
  trial_report: '',
  case_analysis: '',

  // 其他处分信息（补充）
  probation_period_years: null,
  enterprise_level: '',
  escape_destination: '',
  escape_destination_detail: '',

  // 调查信息（补充）
  investigation_suspension_time: '',
  investigation_suspension_stat_time: '',
  capture_time: '',
  capture_stat_time: '',
  case_analysis_report_stat_time: '',

  // 措施信息（补充）
  measure_agency: '',
  measure_agency_name: '',
  detention_start_time: '',
  detention_start_stat_time: '',
  measure_location: '',
  measure_location_category: '',
  detention_end_time: '',
  detention_end_stat_time: '',
  detention_days: null,
  is_extension: '',
  extension_days: null,

  // 特征分类（补充）
  is_masses_problem: '',

  // 组织措施（补充）
  organizational_measures: '',
  organizational_measures_stat_time: '',

  // 其他金额（补充）
  transfer_prosecution_amount: null,

  // 历史措施（补充）
  shuanggui_start_time: '',
  shuanggui_stat_time: '',
  shuanggui_end_time: '',
  shuanggui_end_stat_time: '',

  // 忏悔材料（补充）
  confession: '',

  // 投案信息（补充）
  is_voluntary_surrender: '',
  is_report_to_superior: '',

  // 补充调查（补充）
  is_return_supplementary_investigation: '',
  return_supplementary_time: '',
  return_supplementary_stat_time: '',
  return_supplementary_reason: '',
  is_second_return_supplementary: '',
  second_return_supplementary_time: '',
  second_return_supplementary_stat_time: '',
  second_return_supplementary_reason: '',

  // 不起诉信息（补充）
  is_no_prosecution: '',
  no_prosecution_reason: '',
  no_prosecution_decision_time: '',
  no_prosecution_decision_stat_time: '',

  // 司法信息（补充）
  court_judgment_crime: '',
  public_security_punishment: '',
  public_security_punishment_detail: '',
  transfer_public_security_time: '',
  transfer_public_security_stat_time: '',
  public_security_punishment_time: '',
  public_security_punishment_stat_time: '',

  // 处分变更（补充）
  change_punishment_time: '',
  revoke_punishment_time: '',
  change_punishment_stat_time: '',
  revoke_punishment_stat_time: '',
  change_revoke_reason: '',
  new_party_punishment: '',
  is_new_should_dismiss_but_warning: '',
  new_probation_period_years: null,
  new_administrative_punishment: '',
  new_other_treatment: '',
  new_organizational_measures: '',

  // 从宽处罚建议（补充）
  is_leniency_suggestion: '',
  leniency_suggestion_type: '',
  leniency_suggestion_situation: '',
  leniency_suggestion_stat_time: '',
  is_prosecution_adopt_leniency: '',
  prosecution_adopt_leniency_time: '',
  prosecution_adopt_leniency_stat_time: '',
  is_court_adopt_leniency: '',
  court_adopt_leniency_time: '',
  court_adopt_leniency_stat_time: '',

  // 法律文书（补充）
  prosecution_transfer_opinion: '',

  // 调查措施使用次数（补充）
  freeze_measure_count: null,
  search_measure_count: null,
  seizure_measure_count: null,
  control_measure_count: null,
  tech_investigation_count: null,
  wanted_count: null,
  exit_restriction_count: null,

  // 措施使用情况（补充）
  freeze_measure_situation: '',
  search_measure_situation: '',
  seizure_measure_situation: '',
  control_measure_situation: '',
  tech_investigation_situation: '',
  wanted_measure_situation: '',
  exit_restriction_situation: '',

  // 统计时间（补充）
  measure_usage_stat_time: '',
  remarks_stat_time: '',

  // 纪检监察建议
  suggesting_agency1: '',
  suggested_unit1: '',
  suggestion_type1: '',
  suggestion_content1: '',
  suggestion_time1: '',
  suggesting_agency2: '',
  suggested_unit2: '',
  suggestion_type2: '',
  suggestion_content2: '',
  suggestion_time2: '',

  // 涉外信息
  foreign_related_category: '',
  involved_country: '',
  foreign_related_stat_time: '',
  foreign_related_summary: '',

   // 其他信息（补充）
  unrecovered_overseas_assets: '',
  is_self_handled_case: '',
  is_public_security_transferred_case: '',
  public_security_transferred_detail: '',
  detention_object_identity: '',
  corruption_bribery_time: '',
  corruption_bribery_first_year: '',

  // 备注
  remarks: '',

  // 新增字段 - 党风廉政意见回复情况
  duty_ethics_reply_time: '',
  duty_ethics_reply_type: '',
  duty_ethics_reply_person_count: null,
  duty_ethics_reply_materials: '',

  // 新增字段 - 不如实报告个人有关事项受处理情况
  false_report_handle_time: '',
  false_report_issue: '',
  false_report_disposal: '',
  false_report_punishment_no: '',
  false_report_remarks: '',

  // 新增字段 - 其他反映廉政情况的材料
  other_integrity_material_time: '',
  other_integrity_material_name: '',
  other_integrity_material_content: '',
  other_integrity_material_department: '',
  other_integrity_material_remarks: ''
});
const formRef = ref(null);

const rules = {
  report_unit_name: [
    { required: true, message: '请输入填报单位名称', trigger: 'blur' }
  ],
  investigated_person: [
    { required: true, message: '请输入被调查人', trigger: 'blur' }
  ],
  work_unit_and_position: [
    { required: true, message: '请输入工作单位及职务', trigger: 'blur' }
  ],
  id_number: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ],
  case_code: [
    { required: true, message: '请输入案件编码', trigger: 'blur' }
  ],
  involved_person_code: [
    { required: true, message: '请输入涉案人员编码', trigger: 'blur' }
  ],
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  fileList.value = [];
  selectedFile = null;
};

// 选择文件变化时触发
const handleFileChange = (uploadFile) => {
  fileList.value = [uploadFile];
  selectedFile = uploadFile.raw;
};

// 页面加载时获取数据
onMounted(() => {
  getDisciplineList();
});

const handleSearch = () => {
  pagination.value.currentPage = 1; // 搜索时重置到第一页
  getDisciplineList();
};

// 获取受党纪处分列表
const getDisciplineList = async () => {
  try {
    let query = 'SELECT * FROM discipline_organization_punishment';
    let countQuery = 'SELECT COUNT(*) as total FROM discipline_organization_punishment';
    let params = [];
    
    if (searchName.value && searchName.value.trim()) {
      const whereClause = ' WHERE investigated_person LIKE ?';
      query += whereClause;
      countQuery += whereClause;
      params.push(`%${searchName.value.trim()}%`);
    }
    
    // 添加排序
    query += ' ORDER BY id DESC';
    
    // 添加分页
    const offset = (pagination.value.currentPage - 1) * pagination.value.pageSize;
    query += ` LIMIT ${pagination.value.pageSize} OFFSET ${offset}`;
    
    // 获取总数
    const countResult = await dbClient.query(countQuery, params);
    pagination.value.total = countResult[0].total;
    
    // 获取分页数据
    const data = await dbClient.query(query, params);
    disciplineList.value = data;
  } catch (error) {
    console.error('获取受党纪处分列表失败:', error);
    ElMessage.error('获取受党纪处分列表失败: ' + error.message);
  }
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  pagination.value.currentPage = 1; // 页数大小改变时重置到第一页
  getDisciplineList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  getDisciplineList();
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增受党纪处分记录';
  form.value = {
    // 基本信息
    report_unit_name: '',
    report_unit_code: '',
    investigated_person: '',
    work_unit_and_position: '',
    rank: '',
    cadre_management_authority: '',
    central_managed_cadre_level2: '',
    is_unit_or_accident: '',

    // 案件信息
    case_code: '',
    involved_person_code: '',

    // 个人信息
    id_type: '',
    id_number: '',
    gender: '',
    age: null,
    birth_date: '',
    education: '',
    ethnicity: '',
    is_national_supervision_object: '',
    national_supervision_object_detail: '',
    is_ccp_member: '',
    ccp_congress_representative: '',
    party_join_date: '',
    npc_member: '',
    cppcc_member: '',
    impact_end_date:'',

    // 个人信息（补充）
    non_party_non_supervision: '',
    non_party_non_supervision_detail: '',
    is_discipline_inspection_official: '',
    discipline_inspection_committee: '',
    party_committee: '',
    current_position_start_date: '',
    principal_violation: '',
    principal_detail1: '',
    principal_detail2: '',
    principal_rank: '',
    department_category: '',
    department_category1: '',
    enterprise_nature: '',
    enterprise_nature1: '',
    enterprise_personnel_category: '',
    enterprise_position: '',

    // 金额信息
    misconduct_amount: null,
    total_violation_amount: null,

    // 立案信息
    filing_stat_time: '',
    filing_time: '',
    case_source: '',

     // 立案信息（补充）
    inspection_found_level2: '',
    superior_assigned_level2: '',
    discipline_filing_agency: '',
    discipline_filing_time: '',
    discipline_filing_stat_time: '',
    supervision_filing_agency: '',
    supervision_filing_time: '',
    supervision_filing_stat_time: '',
    is_transferred_after_filing: '',
    transfer_method: '',
    transfer_unit: '',
    brief_case_description: '',
    filing_report: '',
    filing_decision: '',

    // 特征信息（补充）
    is_violate_central_regulations: '',
    is_accountability_case: '',
    is_voluntary_confession: '',

    // 处分信息
    party_discipline_punishment: '',
    is_should_dismiss_but_given_warning: '',
    party_punishment_stat_time: '',
    administrative_punishment: '',
    admin_punishment_stat_time: '',

     // 处分信息（补充）
    other_treatment: '',
    other_treatment_stat_time: '',

    // 司法处理
    transfer_prosecution_time: '',
    criminal_punishment_main: '',
    criminal_punishment_additional: '',
    main_sentence_years: null,
    main_sentence_months: null,

       // 司法处理（补充）
    transfer_prosecution_stat_time: '',
    probation_years: null,
    probation_months: null,
    court_judgment_stat_time: '',

    // 经济处理
    recover_economic_loss: null,
    recovery_amount: null,
    confiscation_amount: null,

        // 经济处理（补充）
    order_refund_amount: null,
    register_submit_amount: null,
    recover_loss_due_to_misconduct: null,

    // 时间信息
    first_violation_time: '',
    last_violation_time: '',
    closing_stat_time: '',
    closing_time: '',

        // 时间信息（补充）
    other_violation_time: '',
    escape_time: '',
    escape_stat_time: '',

    // 审理信息（补充）
    trial_accept_time: '',
    trial_accept_stat_time: '',
    trial_agency: '',
    trial_completion_time: '',
    trial_completion_stat_time: '',
    punishment_decision: '',
    court_judgment_time: '',
    judicial_judgment_amount: null,

    // 报告文件（补充）
    investigation_report: '',
    trial_report: '',
    case_analysis: '',

    // 其他处分信息（补充）
    probation_period_years: null,
    enterprise_level: '',
    escape_destination: '',
    escape_destination_detail: '',

    // 调查信息（补充）
    investigation_suspension_time: '',
    investigation_suspension_stat_time: '',
    capture_time: '',
    capture_stat_time: '',
    case_analysis_report_stat_time: '',

    // 措施信息（补充）
    measure_agency: '',
    measure_agency_name: '',
    detention_start_time: '',
    detention_start_stat_time: '',
    measure_location: '',
    measure_location_category: '',
    detention_end_time: '',
    detention_end_stat_time: '',
    detention_days: null,
    is_extension: '',
    extension_days: null,

    // 特征分类（补充）
    is_masses_problem: '',

    // 组织措施（补充）
    organizational_measures: '',
    organizational_measures_stat_time: '',

    // 其他金额（补充）
    transfer_prosecution_amount: null,

    // 历史措施（补充）
    shuanggui_start_time: '',
    shuanggui_stat_time: '',
    shuanggui_end_time: '',
    shuanggui_end_stat_time: '',

    // 忏悔材料（补充）
    confession: '',

    // 投案信息（补充）
    is_voluntary_surrender: '',
    is_report_to_superior: '',

    // 补充调查（补充）
    is_return_supplementary_investigation: '',
    return_supplementary_time: '',
    return_supplementary_stat_time: '',
    return_supplementary_reason: '',
    is_second_return_supplementary: '',
    second_return_supplementary_time: '',
    second_return_supplementary_stat_time: '',
    second_return_supplementary_reason: '',

    // 不起诉信息（补充）
    is_no_prosecution: '',
    no_prosecution_reason: '',
    no_prosecution_decision_time: '',
    no_prosecution_decision_stat_time: '',

    // 司法信息（补充）
    court_judgment_crime: '',
    public_security_punishment: '',
    public_security_punishment_detail: '',
    transfer_public_security_time: '',
    transfer_public_security_stat_time: '',
    public_security_punishment_time: '',
    public_security_punishment_stat_time: '',

    // 处分变更（补充）
    change_punishment_time: '',
    revoke_punishment_time: '',
    change_punishment_stat_time: '',
    revoke_punishment_stat_time: '',
    change_revoke_reason: '',
    new_party_punishment: '',
    is_new_should_dismiss_but_warning: '',
    new_probation_period_years: null,
    new_administrative_punishment: '',
    new_other_treatment: '',
    new_organizational_measures: '',

    // 从宽处罚建议（补充）
    is_leniency_suggestion: '',
    leniency_suggestion_type: '',
    leniency_suggestion_situation: '',
    leniency_suggestion_stat_time: '',
    is_prosecution_adopt_leniency: '',
    prosecution_adopt_leniency_time: '',
    prosecution_adopt_leniency_stat_time: '',
    is_court_adopt_leniency: '',
    court_adopt_leniency_time: '',
    court_adopt_leniency_stat_time: '',

    // 法律文书（补充）
    prosecution_transfer_opinion: '',

    // 调查措施使用次数（补充）
    freeze_measure_count: null,
    search_measure_count: null,
    seizure_measure_count: null,
    control_measure_count: null,
    tech_investigation_count: null,
    wanted_count: null,
    exit_restriction_count: null,

    // 措施使用情况（补充）
    freeze_measure_situation: '',
    search_measure_situation: '',
    seizure_measure_situation: '',
    control_measure_situation: '',
    tech_investigation_situation: '',
    wanted_measure_situation: '',
    exit_restriction_situation: '',

    // 统计时间（补充）
    measure_usage_stat_time: '',
    remarks_stat_time: '',

    // 纪检监察建议
    suggesting_agency1: '',
    suggested_unit1: '',
    suggestion_type1: '',
    suggestion_content1: '',
    suggestion_time1: '',
    suggesting_agency2: '',
    suggested_unit2: '',
    suggestion_type2: '',
    suggestion_content2: '',
    suggestion_time2: '',

    // 涉外信息
    foreign_related_category: '',
    involved_country: '',
    foreign_related_stat_time: '',
    foreign_related_summary: '',

    // 其他信息（补充）
    unrecovered_overseas_assets: '',
    is_self_handled_case: '',
    is_public_security_transferred_case: '',
    public_security_transferred_detail: '',
    detention_object_identity: '',
    corruption_bribery_time: '',
    corruption_bribery_first_year: '',

    // 备注
    remarks: '',

    // 新增字段 - 党风廉政意见回复情况
    duty_ethics_reply_time: '',
    duty_ethics_reply_type: '',
    duty_ethics_reply_person_count: null,
    duty_ethics_reply_materials: '',

    // 新增字段 - 不如实报告个人有关事项受处理情况
    false_report_handle_time: '',
    false_report_issue: '',
    false_report_disposal: '',
    false_report_punishment_no: '',
    false_report_remarks: '',

    // 新增字段 - 其他反映廉政情况的材料
    other_integrity_material_time: '',
    other_integrity_material_name: '',
    other_integrity_material_content: '',
    other_integrity_material_department: '',
    other_integrity_material_remarks: ''
  };
  dialogVisible.value = true;
};

// 显示编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑受党纪处分记录';
  
  // 将字符串日期转换为 Date 对象
  const processedData = { ...row };
  const dateFields = [
    'filing_time', 'closing_time', 'birth_date', 'party_join_date', 
    'first_violation_time', 'last_violation_time', 'duty_ethics_reply_time',
    'false_report_handle_time', 'other_integrity_material_time',
    'discipline_filing_time','discipline_filing_stat_time',
    'supervision_filing_time','supervision_filing_stat_time',
  ];
  
  dateFields.forEach(field => {
    if (processedData[field]) {
      processedData[field] = new Date(processedData[field]);
    }
  });
  
  form.value = processedData;
  dialogVisible.value = true;
};

// 删除记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('是否要删除当前行数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await dbClient.delete('DELETE FROM discipline_organization_punishment WHERE id = ?', [id]);
    ElMessage.success('删除成功');
    getDisciplineList(searchName.value);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败: ' + error.message);
    }
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 先进行表单验证
    await formRef.value.validate();
  } catch (error) {
    console.log('表单验证失败:', error);
    return;
  }

  // 验证涉案人员编码是否存在于领导人员基本情况表中
  const idNumber = form.value.involved_person_code;
  try {
    const result = await dbClient.query(
      'SELECT id FROM leader_personnel_infro WHERE personnel_code = ?',
      [idNumber]
    );
    
    if (result.length === 0) {
      ElMessage.warning('此领导不存在于领导人员基本情况表中，请验证涉案人员编码是否正确');
      return; // 验证失败，不提交
    }
  } catch (error) {
    console.error('验证身份证号失败:', error);
    ElMessage.error('验证领导人员信息时发生错误');
    return;
  }
  
  // 验证案件编码是否已存在
  const caseCode = form.value.case_code;
  const existingCase = await dbClient.query(
    'SELECT id FROM discipline_organization_punishment WHERE case_code = ?',
    [caseCode]
  );

  // 如果是编辑模式，排除当前记录
  if (form.value.id) {
    const existingRecord = existingCase.find(item => item.id !== form.value.id);
    if (existingRecord) {
      ElMessage.warning('此案件编码重复，请修改');
      return;
    }
  } else {
    // 新增模式，直接检查是否存在
    if (existingCase.length > 0) {
      ElMessage.warning('此案件编码重复，请修改');
      return;
    }
  }
  
  // 处理表单数据：日期格式转换
  const formData = { ...form.value };
  
  // 需要转换为字符串的日期字段
  const dateFields = [
    'impact_end_date',
    'filing_time', 'closing_time', 'birth_date', 'party_join_date',
    'first_violation_time', 'last_violation_time', 'filing_stat_time',
    'party_punishment_stat_time', 'admin_punishment_stat_time',
    'transfer_prosecution_time', 'closing_stat_time',
    'suggestion_time1', 'suggestion_time2', 'foreign_related_stat_time',
    // 新增日期字段
    'duty_ethics_reply_time', 'false_report_handle_time', 'other_integrity_material_time',
    'discipline_filing_time','discipline_filing_stat_time',
    'supervision_filing_time','supervision_filing_stat_time',
  ];

  // 转换日期为 YYYY-MM-DD 字符串
  dateFields.forEach(field => {
    if (formData[field] && formData[field] instanceof Date && !isNaN(formData[field].getTime())) {
      const year = formData[field].getFullYear();
      const month = String(formData[field].getMonth() + 1).padStart(2, '0');
      const day = String(formData[field].getDate()).padStart(2, '0');
      const hours = String(formData[field].getHours()).padStart(2, '0');
      const minutes = String(formData[field].getMinutes()).padStart(2, '0');
      const seconds = String(formData[field].getSeconds()).padStart(2, '0');
      
      // 对于日期时间字段，使用完整的时间格式
      if (field.includes('_time') && (field.includes('duty_ethics') || field.includes('false_report') || field.includes('other_integrity'))) {
        formData[field] = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } else {
        formData[field] = `${year}-${month}-${day}`;
      }
    }
  });

  // 提取字段名和值
  const fields = Object.keys(formData).filter(key => key !== 'id');
  const values = fields.map(key => formData[key]);

  try {
    if (formData.id) {
      // 编辑：更新数据
      const setClause = fields.map(field => `${field} = ?`).join(', ');
      const updateValues = [...values, formData.id];
      await dbClient.update(
        `UPDATE discipline_organization_punishment SET ${setClause} WHERE id = ?`,
        updateValues
      );
      ElMessage.success('更新成功');
    } else {
      // 新增：插入数据
      const placeholders = fields.map(() => '?').join(',');
      await dbClient.insert(
        `INSERT INTO discipline_organization_punishment (${fields.join(', ')}) VALUES (${placeholders})`,
        values
      );
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    getDisciplineList(searchName.value);
  } catch (error) {
    console.error('保存失败:', error);
    if (error.message.includes('can only bind numbers, strings')) {
      ElMessage.error('保存失败: 日期格式转换错误，请确保选择了有效的日期');
    } else {
      ElMessage.error('保存失败: ' + error.message);
    }
  }
};

// 完整的字段映射：Excel列名 -> 数据库表字段名
const fieldMap = {
  // 基本信息
  '填报单位名称': 'report_unit_name',
  '填报单位代码': 'report_unit_code',
  '被调查人': 'investigated_person',
  '工作单位及职务': 'work_unit_and_position',
  '职级': 'rank',
  '干部管理权限': 'cadre_management_authority',
  '中管干部二级': 'central_managed_cadre_level2',
  '是否单位或事故': 'is_unit_or_accident',
  
  // 案件信息
  '案件编码': 'case_code',
  '涉案人员编码': 'involved_person_code',
  
  // 个人信息
  '证件类型': 'id_type',
  '证件号码': 'id_number',
  '性别': 'gender',
  '年龄': 'age',
  '出生年月': 'birth_date',
  '学历': 'education',
  '民族': 'ethnicity',
  '是否国家监察对象': 'is_national_supervision_object',
  '国家监察对象详情': 'national_supervision_object_detail',
  '是否中共党员': 'is_ccp_member',
  '中共党代表': 'ccp_congress_representative',
  '入党时间': 'party_join_date',
  '非党员非监察对象': 'non_party_non_supervision',
  '非党员非监察对象详情': 'non_party_non_supervision_detail',
  '人大代表': 'npc_member',
  '政协委员': 'cppcc_member',
  '影响期限结束日期':'impact_end_date',
  '是否纪检监察干部': 'is_discipline_inspection_official',
  '纪委委员': 'discipline_inspection_committee',
  '党委委员': 'party_committee',
  '任现职时间': 'current_position_start_date',
  '一把手违纪违法': 'principal_violation',
  '一把手细节': 'principal_detail1',
  '一把手细节2': 'principal_detail2',
  '正副职级': 'principal_rank',
  '部门分类': 'department_category',
  '部门分类1': 'department_category1',
  '企业性质': 'enterprise_nature',
  '企业性质1': 'enterprise_nature1',
  '企业人员类别': 'enterprise_personnel_category',
  '企业岗位': 'enterprise_position',
  
  // 金额信息
  '失职渎职金额': 'misconduct_amount',
  '违纪违法总金额（万元）': 'total_violation_amount',
  
  // 立案信息
  '立案统计时间': 'filing_stat_time',
  '立案时间': 'filing_time',
  '案件来源': 'case_source',
  '巡视巡察中发现二级分类': 'inspection_found_level2',
  '上级交办转办二级分类': 'superior_assigned_level2',
  '纪委立案机关': 'discipline_filing_agency',
  '纪委立案时间': 'discipline_filing_time',
  '纪委立案统计时间': 'discipline_filing_stat_time',
  '监委立案机关': 'supervision_filing_agency',
  '监委立案时间': 'supervision_filing_time',
  '监委立案统计时间': 'supervision_filing_stat_time',
  '是否其他纪检监察机关立案后移送': 'is_transferred_after_filing',
  '立案后移送方式': 'transfer_method',
  '移送单位': 'transfer_unit',
  '简要案情': 'brief_case_description',
  '立案报告': 'filing_report',
  '立案决定书': 'filing_decision',
  
  // 特征信息
  '是否违反中央八项规定精神': 'is_violate_central_regulations',
  '是否属于问责': 'is_accountability_case',
  '是否主动交代问题': 'is_voluntary_confession',
  
  // 结案信息
  '结案统计时间': 'closing_stat_time',
  '销案时间': 'case_cancellation_time',
  '结案时间': 'closing_time',
  
  // 处分信息
  '党纪处分': 'party_discipline_punishment',
  '是否本应撤销党内职务但给予严重警告': 'is_should_dismiss_but_given_warning',
  '党纪处分统计时间': 'party_punishment_stat_time',
  '政务处分': 'administrative_punishment',
  '政务处分统计时间': 'admin_punishment_stat_time',
  '其他处理': 'other_treatment',
  '其他处理统计时间': 'other_treatment_stat_time',
  
  // 司法处理
  '移送检察机关时间': 'transfer_prosecution_time',
  '移送检察机关统计时间': 'transfer_prosecution_stat_time',
  '刑事处理主刑': 'criminal_punishment_main',
  '刑事处理附加刑': 'criminal_punishment_additional',
  '主刑年数': 'main_sentence_years',
  '主刑月数': 'main_sentence_months',
  '缓刑年数': 'probation_years',
  '缓刑月数': 'probation_months',
  '审判机关判决统计时间': 'court_judgment_stat_time',
  
  // 经济处理
  '挽回经济损失（万元）': 'recover_economic_loss',
  '收缴金额（万元）': 'recovery_amount',
  '没收金额': 'confiscation_amount',
  '责令退赔金额': 'order_refund_amount',
  '登记上交金额': 'register_submit_amount',
  '追缴失职渎职滥用职权造成的损失金额': 'recover_loss_due_to_misconduct',
  
  // 时间信息
  '首次违纪违法时间': 'first_violation_time',
  '末次违纪违法时间': 'last_violation_time',
  '其他违纪违法时间': 'other_violation_time',
  '潜逃时间': 'escape_time',
  '潜逃统计时间': 'escape_stat_time',
  
  // 审理信息
  '审理受理时间': 'trial_accept_time',
  '审理受理统计时间': 'trial_accept_stat_time',
  '审理机关': 'trial_agency',
  '审结时间': 'trial_completion_time',
  '审结统计时间': 'trial_completion_stat_time',
  '处分决定': 'punishment_decision',
  '审判机关判决时间': 'court_judgment_time',
  '司法判决金额（万元）': 'judicial_judgment_amount',

  // 报告文件
  '审查调查报告': 'investigation_report',
  '审理报告': 'trial_report',
  '案件剖析': 'case_analysis',
  
  // 其他处分信息
  '留党察看年限': 'probation_period_years',
  '企业级别': 'enterprise_level',
  '潜逃去向': 'escape_destination',
  '潜逃去向细节': 'escape_destination_detail',
  
  // 调查信息
  '调查中止时间': 'investigation_suspension_time',
  '调查中止统计时间': 'investigation_suspension_stat_time',
  '抓获时间': 'capture_time',
  '抓获统计时间': 'capture_stat_time',
  '案件剖析报告统计时间': 'case_analysis_report_stat_time',
  
  // 措施信息
  '采取措施机关': 'measure_agency',
  '采取措施机关名称': 'measure_agency_name',
  '留置起始时间': 'detention_start_time',
  '留置起始统计时间': 'detention_start_stat_time',
  '采取措施地点': 'measure_location',
  '采取措施地点分类': 'measure_location_category',
  '留置结束时间': 'detention_end_time',
  '留置结束统计时间': 'detention_end_stat_time',
  '留置天数': 'detention_days',
  '是否延期': 'is_extension',
  '延期天数': 'extension_days',

  // 特征分类
  '是否群众身边的不正之风和腐败问题': 'is_masses_problem',
  
  // 组织措施
  '组织措施': 'organizational_measures',
  '组织措施统计时间': 'organizational_measures_stat_time',

  // 其他金额
  '移送检察机关金额（万元）': 'transfer_prosecution_amount',
  
  // 历史措施
  '两规两指起始时间': 'shuanggui_start_time',
  '两规两指统计时间': 'shuanggui_stat_time',
  '两规两指解除时间': 'shuanggui_end_time',
  '两规两指解除统计时间': 'shuanggui_end_stat_time',

  // 忏悔材料
  '忏悔书': 'confession',
  
  // 投案信息
  '是否主动投案': 'is_voluntary_surrender',
  '是否属于向上级纪委监委报告范围': 'is_report_to_superior',
  
  // 补充调查
  '是否退回补充调查': 'is_return_supplementary_investigation',
  '退回补充调查时间': 'return_supplementary_time',
  '退回补充调查统计时间': 'return_supplementary_stat_time',
  '退回补充调查原因': 'return_supplementary_reason',
  '是否二次退回补充调查': 'is_second_return_supplementary',
  '二次退回补充调查时间': 'second_return_supplementary_time',
  '二次退回补充调查统计时间': 'second_return_supplementary_stat_time',
  '二次退回补充调查原因': 'second_return_supplementary_reason',
  
  // 不起诉信息
  '是否不起诉': 'is_no_prosecution',
  '不起诉原因': 'no_prosecution_reason',
  '决定不起诉时间': 'no_prosecution_decision_time',
  '决定不起诉统计时间': 'no_prosecution_decision_stat_time',
  
  // 司法信息
  '审判机关判决罪名': 'court_judgment_crime',
  '公安等其他行政法机关处罚': 'public_security_punishment',
  '公安等其他行政法机关处罚详细内容': 'public_security_punishment_detail',
  '移送公安机关时间': 'transfer_public_security_time',
  '移送公安机关统计时间': 'transfer_public_security_stat_time',
  '公安等其他行政法机关处罚时间': 'public_security_punishment_time',
  '公安等其他行政法机关处罚统计时间': 'public_security_punishment_stat_time',
  
  // 处分变更
  '变更处分时间': 'change_punishment_time',
  '撤销处分时间': 'revoke_punishment_time',
  '变更处分统计时间': 'change_punishment_stat_time',
  '撤销处分统计时间': 'revoke_punishment_stat_time',
  '变更撤销原因': 'change_revoke_reason',
  '新党纪处分': 'new_party_punishment',
  '新党纪处分是否属于"本应撤销党内职务但给予严重警告"': 'is_new_should_dismiss_but_warning',
  '新留党察看年限': 'new_probation_period_years',
  '新政务处分': 'new_administrative_punishment',
  '新其他处理': 'new_other_treatment',
  '新组织措施': 'new_organizational_measures',
  
  // 从宽处罚建议
  '监察机关是否提出从宽处罚建议': 'is_leniency_suggestion',
  '从宽处罚建议类型': 'leniency_suggestion_type',
  '监察机关提出从宽处罚建议的情形': 'leniency_suggestion_situation',
  '提出从宽处罚建议统计时间': 'leniency_suggestion_stat_time',
  '检察机关是否采纳从宽处罚建议': 'is_prosecution_adopt_leniency',
  '检察机关采纳从宽处罚建议时间': 'prosecution_adopt_leniency_time',
  '检察机关采纳从宽处罚建议统计时间': 'prosecution_adopt_leniency_stat_time',
  '审判机关是否采纳从宽处罚建议': 'is_court_adopt_leniency',
  '审判机关采纳从宽处罚建议时间': 'court_adopt_leniency_time',
  '审判机关采纳从宽处罚建议统计时间': 'court_adopt_leniency_stat_time',

  // 法律文书
  '纪检监察机关移送检察机关起诉意见书': 'prosecution_transfer_opinion',
  
  // 调查措施使用次数
  '冻结措施使用次数': 'freeze_measure_count',
  '搜查措施使用次数': 'search_measure_count',
  '查封使用次数': 'seizure_measure_count',
  '扣押使用次数': 'control_measure_count',
  '技术调查使用次数': 'tech_investigation_count',
  '通缉使用次数': 'wanted_count',
  '限制出境使用次数': 'exit_restriction_count',

  // 措施使用情况
  '冻结措施使用情况': 'freeze_measure_situation',
  '搜查措施使用情况': 'search_measure_situation',
  '查封措施使用情况': 'seizure_measure_situation',
  '扣押措施使用情况': 'control_measure_situation',
  '技术调查措施使用情况': 'tech_investigation_situation',
  '通缉措施使用情况': 'wanted_measure_situation',
  '限制出境措施使用情况': 'exit_restriction_situation',

  // 统计时间
  '使用措施统计时间': 'measure_usage_stat_time',
  '备注统计时间': 'remarks_stat_time',
  
  // 纪检监察建议（8条完整）
  '提出建议的纪检监察机构名称1': 'suggesting_agency1',
  '被建议的单位（组织）名称1': 'suggested_unit1',
  '建议类型1': 'suggestion_type1',
  '建议文书内容1': 'suggestion_content1',
  '提出建议时间1': 'suggestion_time1',
  '提出建议统计时间1': 'suggestion_stat_time1',
  
  '提出建议的纪检监察机构名称2': 'suggesting_agency2',
  '被建议的单位（组织）名称2': 'suggested_unit2',
  '建议类型2': 'suggestion_type2',
  '建议文书内容2': 'suggestion_content2',
  '提出建议时间2': 'suggestion_time2',
  '提出建议统计时间2': 'suggestion_stat_time2',
  
  '提出建议的纪检监察机构名称3': 'suggesting_agency3',
  '被建议的单位（组织）名称3': 'suggested_unit3',
  '建议类型3': 'suggestion_type3',
  '建议文书内容3': 'suggestion_content3',
  '提出建议时间3': 'suggestion_time3',
  '提出建议统计时间3': 'suggestion_stat_time3',
  
  '提出建议的纪检监察机构名称4': 'suggesting_agency4',
  '被建议的单位（组织）名称4': 'suggested_unit4',
  '建议类型4': 'suggestion_type4',
  '建议文书内容4': 'suggestion_content4',
  '提出建议时间4': 'suggestion_time4',
  '提出建议统计时间4': 'suggestion_stat_time4',
  
  '提出建议的纪检监察机构名称5': 'suggesting_agency5',
  '被建议的单位（组织）名称5': 'suggested_unit5',
  '建议类型5': 'suggestion_type5',
  '建议文书内容5': 'suggestion_content5',
  '提出建议时间5': 'suggestion_time5',
  '提出建议统计时间5': 'suggestion_stat_time5',
  
  '提出建议的纪检监察机构名称6': 'suggesting_agency6',
  '被建议的单位（组织）名称6': 'suggested_unit6',
  '建议类型6': 'suggestion_type6',
  '建议文书内容6': 'suggestion_content6',
  '提出建议时间6': 'suggestion_time6',
  '提出建议统计时间6': 'suggestion_stat_time6',
  
  '提出建议的纪检监察机构名称7': 'suggesting_agency7',
  '被建议的单位（组织）名称7': 'suggested_unit7',
  '建议类型7': 'suggestion_type7',
  '建议文书内容7': 'suggestion_content7',
  '提出建议时间7': 'suggestion_time7',
  '提出建议统计时间7': 'suggestion_stat_time7',
  
  '提出建议的纪检监察机构名称8': 'suggesting_agency8',
  '被建议的单位（组织）名称8': 'suggested_unit8',
  '建议类型8': 'suggestion_type8',
  '建议文书内容8': 'suggestion_content8',
  '提出建议时间8': 'suggestion_time8',
  '提出建议统计时间8': 'suggestion_stat_time8',
  
  // 涉外信息
  '涉外类别': 'foreign_related_category',
  '涉及国家（地区）': 'involved_country',
  '涉外统计时间': 'foreign_related_stat_time',
  '涉外信息摘要': 'foreign_related_summary',
  
  // 其他信息
  '尚未追回的境外涉案财物': 'unrecovered_overseas_assets',
  '纪检监察机关自办案件': 'is_self_handled_case',
  '公检法等机关移送的非职务违法犯罪等案件': 'is_public_security_transferred_case',
  '公检法等机关移送的非职务违法犯罪等案件二级分类': 'public_security_transferred_detail',
  '留置对象身份': 'detention_object_identity',
  '贪污贿赂行为发生时间': 'corruption_bribery_time',
  '贪污贿赂行为的首次年份': 'corruption_bribery_first_year',
  
  // 备注
  '备注': 'remarks',
  
  // 新增字段映射
  // 党风廉政意见回复情况
  '党风廉政意见回复时间': 'duty_ethics_reply_time',
  '党风廉政意见回复类型': 'duty_ethics_reply_type',
  '党风廉政意见回复涉及人次': 'duty_ethics_reply_person_count',
  '党风廉政意见回复材料': 'duty_ethics_reply_materials',
  
  // 不如实报告个人有关事项受处理情况
  '不如实报告处理时间': 'false_report_handle_time',
  '不如实报告问题': 'false_report_issue',
  '不如实报告处理情况': 'false_report_disposal',
  '不如实报告处分文号': 'false_report_punishment_no',
  '不如实报告备注': 'false_report_remarks',
  
  // 其他反映廉政情况的材料
  '其他廉政材料时间': 'other_integrity_material_time',
  '其他廉政材料名称': 'other_integrity_material_name',
  '其他廉政材料内容': 'other_integrity_material_content',
  '其他廉政材料形成部门': 'other_integrity_material_department',
  '其他廉政材料备注': 'other_integrity_material_remarks'
};

// 提交导入数据
const submitImport = async () => {
  if (!selectedFile) {
    ElMessage.warning('请选择要导入的Excel文件');
    return;
  }
  
  try {
    // 解析Excel文件
    const fileReader = new FileReader();
    fileReader.readAsBinaryString(selectedFile);
    fileReader.onload = async (event) => {
      const workbook = XLSX.read(event.target.result, { type: 'binary' });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const excelData = XLSX.utils.sheet_to_json(worksheet);
      
      if (excelData.length === 0) {
        ElMessage.warning('Excel文件中无数据');
        return;
      }

      // 完整的日期字段列表（根据表结构提取）
      const dateFields = [
        'impact_end_date',
        'birth_date', 'party_join_date', 'filing_time', 'filing_stat_time',
        'closing_time', 'closing_stat_time', 'first_violation_time', 'last_violation_time',
        'other_violation_time', 'escape_time', 'escape_stat_time', 'party_punishment_stat_time',
        'admin_punishment_stat_time', 'transfer_prosecution_time', 'transfer_prosecution_stat_time',
        'court_judgment_stat_time', 'trial_accept_time', 'trial_accept_stat_time',
        'trial_completion_time', 'trial_completion_stat_time', 'court_judgment_time',
        'investigation_suspension_time', 'investigation_suspension_stat_time',
        'capture_time', 'capture_stat_time', 'case_analysis_report_stat_time',
        'detention_start_time', 'detention_start_stat_time', 'detention_end_time',
        'detention_end_stat_time', 'organizational_measures_stat_time',
        'shuanggui_start_time', 'shuanggui_stat_time', 'shuanggui_end_time', 'shuanggui_end_stat_time',
        'return_supplementary_time', 'return_supplementary_stat_time',
        'second_return_supplementary_time', 'second_return_supplementary_stat_time',
        'no_prosecution_decision_time', 'no_prosecution_decision_stat_time',
        'transfer_public_security_time', 'transfer_public_security_stat_time',
        'public_security_punishment_time', 'public_security_punishment_stat_time',
        'change_punishment_time', 'revoke_punishment_time', 'change_punishment_stat_time', 'revoke_punishment_stat_time',
        'leniency_suggestion_stat_time', 'prosecution_adopt_leniency_time', 'prosecution_adopt_leniency_stat_time',
        'court_adopt_leniency_time', 'court_adopt_leniency_stat_time',
        'current_position_start_date', 'discipline_filing_time', 'discipline_filing_stat_time',
        'supervision_filing_time', 'supervision_filing_stat_time', 'case_cancellation_time',
        'other_treatment_stat_time', 'corruption_bribery_time',
        // 纪检监察建议相关日期字段
        'suggestion_time1', 'suggestion_stat_time1', 'suggestion_time2', 'suggestion_stat_time2',
        'suggestion_time3', 'suggestion_stat_time3', 'suggestion_time4', 'suggestion_stat_time4',
        'suggestion_time5', 'suggestion_stat_time5', 'suggestion_time6', 'suggestion_stat_time6',
        'suggestion_time7', 'suggestion_stat_time7', 'suggestion_time8', 'suggestion_stat_time8',
        // 涉外信息日期字段
        'foreign_related_stat_time',
        // 新增日期字段
        'duty_ethics_reply_time', 'false_report_handle_time', 'other_integrity_material_time'
      ];
      
      // 完整的数字字段列表（根据表结构提取）
      const numberFields = [
        'misconduct_amount', 'total_violation_amount', 'recover_economic_loss',
        'recovery_amount', 'confiscation_amount', 'order_refund_amount',
        'register_submit_amount', 'recover_loss_due_to_misconduct', 'age',
        'main_sentence_years', 'main_sentence_months', 'probation_years', 'probation_months',
        'judicial_judgment_amount', 'detention_days', 'extension_days',
        'transfer_prosecution_amount', 'new_probation_period_years',
        // 调查措施使用次数
        'freeze_measure_count', 'search_measure_count', 'seizure_measure_count',
        'control_measure_count', 'tech_investigation_count', 'wanted_count', 'exit_restriction_count',
        // 其他数字字段
        'probation_period_years',
        // 新增数字字段
        'duty_ethics_reply_person_count'
      ];

      // 数据处理：字段映射 + 格式转换
      const importData = [];
      for (const item of excelData) {
        const formattedItem = {};
        let isItemValid = true;

        // 1. 字段映射（Excel列名 → 数据库表字段）
        Object.keys(fieldMap).forEach(excelField => {
          const dbField = fieldMap[excelField];
          formattedItem[dbField] = item[excelField] || '';
        });

        // 2. 日期格式处理（兼容Excel数字/文本格式，统一转为YYYY-MM-DD）
        dateFields.forEach(dbField => {
          const excelValue = formattedItem[dbField];
          if (!excelValue) return;

          try {
            let dateObj;
            if (typeof excelValue === 'number') {
              // 处理Excel数字格式日期（如44927 → 2023-01-01）
              const dateCode = XLSX.SSF.parse_date_code(excelValue, { date1904: false });
              dateObj = new Date(dateCode.y, dateCode.m - 1, dateCode.d);
            } else if (typeof excelValue === 'string') {
              // 处理文本格式日期（如"2023-10-01"、"5/31/25"）
              dateObj = new Date(excelValue);
            } else {
              isItemValid = false;
              ElMessage.warning(`数据【${formattedItem.investigated_person || '未知'}】的${dbField}字段格式无效`);
              return;
            }

            if (isNaN(dateObj.getTime())) {
              isItemValid = false;
              ElMessage.warning(`数据【${formattedItem.investigated_person || '未知'}】的${dbField}字段日期无效（${excelValue}）`);
              return;
            }

            // 对于日期时间字段，使用完整的时间格式
            if (dbField.includes('_time') && (dbField.includes('duty_ethics') || dbField.includes('false_report') || dbField.includes('other_integrity'))) {
              formattedItem[dbField] = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')} ${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}:${String(dateObj.getSeconds()).padStart(2, '0')}`;
            } else {
              formattedItem[dbField] = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`;
            }
          } catch (error) {
            isItemValid = false;
            ElMessage.warning(`数据【${formattedItem.investigated_person || '未知'}】的${dbField}字段解析失败：${error.message}`);
          }
        });

        // 3. 数字格式处理（空值转null，非负验证）
        numberFields.forEach(dbField => {
          const excelValue = formattedItem[dbField];
          if (excelValue === '' || excelValue === null || excelValue === undefined) {
            formattedItem[dbField] = null;
            return;
          }

          const numericValue = Number(excelValue);
          if (isNaN(numericValue) || numericValue < 0) {
            isItemValid = false;
            ElMessage.warning(`数据【${formattedItem.investigated_person || '未知'}】的${dbField}字段需为非负数字`);
          } else {
            formattedItem[dbField] = numericValue;
          }
        });

        // 在日期格式处理和数字格式处理之后，添加文本字段处理，2025.11.26
          const textFields = ['report_unit_code']; // 可以扩展其他需要强制转换为文本的字段
          textFields.forEach(dbField => {
              if (formattedItem[dbField] !== null && formattedItem[dbField] !== undefined) {
                formattedItem[dbField] = String(formattedItem[dbField]);
              }
            });

        // 保留有效数据
        if (isItemValid) {
          importData.push(formattedItem);
        }
      }

      // 4. 验证必填字段（对应auth.js表必填约束）
      const requiredFields = ['report_unit_name', 'investigated_person', 'work_unit_and_position', 'case_code', 'id_number','involved_person_code'];
      const validData = importData.filter(item => {
        const hasAllRequired = requiredFields.every(field => {
          const rawValue = item[field];
          const processedValue = rawValue === undefined || rawValue === null ? '' : String(rawValue).trim();
          return processedValue !== '';
        });

        if (!hasAllRequired) {
          const missingFields = requiredFields.filter(field => {
            const rawValue = item[field];
            const processedValue = rawValue === undefined || rawValue === null ? '' : String(rawValue).trim();
            return processedValue === '';
          });
          ElMessage.warning(`数据【${item.investigated_person || '未知人员'}】缺少必填字段：${missingFields.join('、')}，已过滤`);
        }
        return hasAllRequired;
      });

      const invalidCount = importData.length - validData.length;
      if (invalidCount > 0) {
        ElMessage.warning(`共${invalidCount}条数据无效（格式错误/缺少必填项），已过滤`);
      }
      if (validData.length === 0) {
        ElMessage.error('无有效数据可导入');
        return;
      }

      // 5. 额外验证（涉案人员编码的存在性）
      const finalValidData = [];
      for (const item of validData) {
        item.involved_person_code = item.involved_person_code.toString().trim();
        // 验证涉案人员编码是否存在于领导人员表（auth.js中leader_personnel_infro表的personnel_code字段）
        const involvedPersonCode = await dbClient.query(
          'SELECT id FROM leader_personnel_infro WHERE personnel_code = ?',
          [item.involved_person_code]
        );
        if (involvedPersonCode.length === 0) {
          ElMessage.warning(`数据【${item.investigated_person}】的涉案人员编码不存在于领导人员表，已过滤`);
          continue;
        }

        finalValidData.push(item);
      }

      if (finalValidData.length === 0) {
        ElMessage.error('无有效数据可导入（身份证号不存在）');
        return;
      }

      // 6. 批量导入数据库（适配auth.js表结构）
      try {
        const fields = Object.values(fieldMap);
        const placeholders = fields.map(() => '?').join(',');
        const values = finalValidData.map(item => fields.map(field => item[field]));

        await dbClient.batchInsert(
          `INSERT OR REPLACE INTO discipline_organization_punishment (${fields.join(', ')}) VALUES (${placeholders})`,
          values
        );

        ElMessage.success(`成功导入${finalValidData.length}条受党纪处分数据,(新增或更新)`);
        importDialogVisible.value = false;
        getDisciplineList(searchName.value); // 重新加载列表
      } catch (dbError) {
        console.error('数据库导入失败:', dbError);
        ElMessage.error(`导入失败：${dbError.message}`);
      }
    };
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + error.message);
  }
};

// 导出数据到 Excel
const exportData = async () => {
  let loadingInstance = null;
  try {
    // 显示加载特效
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在导出数据，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 构建查询条件（与搜索条件一致）
    let query = 'SELECT * FROM discipline_organization_punishment';
    let params = [];
    
    if (searchName.value && searchName.value.trim()) {
      query += ' WHERE investigated_person LIKE ?';
      params.push(`%${searchName.value.trim()}%`);
    }
    
    // 添加排序
    query += ' ORDER BY id DESC';
    
    // 获取所有符合条件的数据（不分页）
    const data = await dbClient.query(query, params);
    
    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可导出');
      return;
    }
    
    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    
    // 创建反向映射：数据库字段名 -> 中文名称
    const reverseFieldMap = {};
    Object.keys(fieldMap).forEach(chineseName => {
      const dbField = fieldMap[chineseName];
      reverseFieldMap[dbField] = chineseName;
    });
    
    // 定义需要排除的字段
    const excludedFields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by'];
    
    // 准备表头和数据 - 过滤掉不需要的字段
    const allFields = Object.keys(data[0]);
    const filteredFields = allFields.filter(field => !excludedFields.includes(field));
    
    const headers = filteredFields.map(field => reverseFieldMap[field] || field);
    const excelData = [
      headers, // 第一行是中文表头
      ...data.map(row => 
        filteredFields.map(field => {
          // 处理日期字段，确保格式正确
          const value = row[field];
          if (value && typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}/)) {
            return value; // 保持日期格式
          }
          return value || '';
        })
      )
    ];
    
    // 创建工作表
    const worksheet = XLSX.utils.aoa_to_sheet(excelData);
    
    // 设置列宽自适应
    const colWidths = headers.map(header => ({
      wch: Math.max(header.length, 10) // 最小宽度10，根据内容调整
    }));
    worksheet['!cols'] = colWidths;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '受党纪处分和组织处理情况');
    
    // 生成带时分秒的文件名
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
    const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
    const fileName = `受党纪处分和组织处理情况_${dateStr}_${timeStr}.xlsx`;
    
    // 生成 Excel 文件并下载
    XLSX.writeFile(workbook, fileName);
    
    ElMessage.success(`成功导出 ${data.length} 条数据`);
    
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error(`导出失败: ${error.message || '未知错误'}`);
  } finally {
    // 关闭加载特效
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f6f7;
}

.card-container {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
}

.full-height-card {
  height: 99%;
  display: flex;
  flex-direction: column;
  background: #f5f6f7;
  margin: 10px;
}

:deep(.el-card__header) {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;
  background: white;
}

:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  background: #f5f6f7;
}

.table-wrapper {
  margin: 20px 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.full-height-table {
  width: 100%;
}

.action-bar {
  margin: 15px 15px 15px 15px;
  padding: 5px;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

.action-bar .el-button {
  min-width: 100px;
  height: 40px;
  font-size: 16px;
  font-weight: 500;
}

.action-bar .el-input {
  margin-right: 10px;
}

@media (max-width: 768px) {
  .action-bar .el-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .action-bar .el-col {
    width: 100%;
  }
  
  .button-group {
    justify-content: center;
  }
}

.card-container {
  flex: 1;
  padding: 10px 20px 20px 20px;
  box-sizing: border-box;
}

.table-wrapper {
  margin: 10px 0;
}

:deep(.el-table__header th .cell) {
  font-weight: bold;
  font-size: 18px;
  color: #1d1d1da9;
}

:deep(.el-table__body td .cell) {
  font-size: 18px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
}

/* 分割线样式优化 */
:deep(.el-divider__text) {
  font-weight: bold;
  color: #409EFF;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 自定义折叠面板样式 */
.custom-collapse {
  margin-top: 20px;
  width: 98%;
}

:deep(.custom-collapse .el-collapse-item__header) {
  font-weight: 600;
  font-size: 16px;
  background-color: #f8f9fa;
  padding: 0 10px;
  height: 48px;
  line-height: 48px;
  border-radius: 4px;
  justify-content: center;
}

:deep(.custom-collapse .el-collapse-item__wrap) {
  background-color: #fff;
  border-bottom: none;
}

:deep(.custom-collapse .el-collapse-item__content) {
  padding: 16px;
  background-color: #fafbfc;
  border-radius: 0 0 4px 4px;
}

:deep(.custom-collapse .el-form-item) {
  margin-bottom: 16px;
}
</style>